package net.sunofbeach.blog.service.impl;

import net.sunofbeach.blog.pojo.User;
import net.sunofbeach.blog.service.UserService;
import net.sunofbeach.blog.utils.Constants;
import net.sunofbeach.blog.utils.CookieUtils;
import net.sunofbeach.blog.utils.TextUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bing_  @create 2021/11/30-10:37
 */
@Service("permission")
public class PermissionService {
    
    @Resource
    private UserService userService;

    /**
     * 判断是不是管理员
     * @return
     */
    public boolean admin(){

        // 拿到 request 和 response
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKEN_KEY);
        // 没有令牌的 key，没有登录，不往下执行
        if (TextUtils.isEmpty(tokenKey)) {
            return false;
        }
        User user = userService.checkSobUser();
        if (user == null) {
            return false;
        }
        if (Constants.User.ROLE_ADMIN.equals(user.getRole())) {
            return true;
        }
        return false;
    }
}
